package com.xunk.system.factory;

import com.xunk.system.service.ISysDeviceService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ProjectName: xunk
 * @Package: com.xunk.buz.factory
 * @ClassName: SysDeviceServiceFactory
 * @Author: luanzhiwei
 * @Description: 设备service工厂类，用于获取不同实现类
 * @Date: 2021/3/30 9:55
 * @Version: 1.0
 */
@Component
public class SysDeviceServiceFactory {

    @Autowired
    Map<String, ISysDeviceService> concurrentHashMap = new ConcurrentHashMap<>();

    /**
     * 获取spring中的实现类，默认返回sysDeviceServiceImpl
     *
     * @param serviceName
     * @return
     * @throws Exception
     */
    public ISysDeviceService getSysDeviceService(String serviceName) throws Exception {
        String service = ServiceEnum.getService(serviceName);
        ISysDeviceService sysDeviceService = concurrentHashMap.get(service);
        if (ObjectUtils.isEmpty(sysDeviceService)) {
            throw new Exception("设备service工厂类，获取实现类出错！");
        }
        return sysDeviceService;
    }

    /**
     * 将工厂类入参serviceName映射到service实现类在spring bean工厂中的名称
     */
    private enum ServiceEnum {

        MANDUN("mandun", "mandunDeviceServiceImpl"),
        RUYING("ruying", "sysDeviceServiceImpl");
        /**
         * 接口入参
         */
        private String key;
        /**
         * spring bean工厂中管理的service名称
         */
        private String service;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getService() {
            return service;
        }

        public static String getService(String key) {
            for (ServiceEnum value : ServiceEnum.values()) {
                if (value.getKey().equals(key)) {
                    return value.getService();
                }
            }
            return RUYING.getService();
        }

        public void setService(String service) {
            this.service = service;
        }

        ServiceEnum(String key, String service) {
            this.key = key;
            this.service = service;
        }

        ServiceEnum() {
        }
    }

}
